package library.net.retrofit.interceptor;

import java.io.IOException;

import library.common.util.NetworkUtil;
import library.net.RxRetrofitUtils;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Cache-Time: user-defined cache max time
 *
 * @author Created by qiang.hou on 2017/11/19.
 * @version 1.0
 */
public class RxCacheInterceptor implements Interceptor {

    public RxCacheInterceptor() {
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        if (NetworkUtil.isNetworkAvailable(RxRetrofitUtils.getInstance().getApplication())) {
            Response oldResponse = chain.proceed(request);
            /* Cache-Time is the params user-defined from header, value is the time available */
            String cacheTime = request.header("Cache-Time");
            if (null != cacheTime) {
                return oldResponse.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        /* cache for cache seconds */
                        .header("Cache-Control", "max-age=" + cacheTime)
                        .build();
            } else {
                return oldResponse;
            }
        }
        // 如果没有网络，不做处理，交给RxNetCacheInterceptor处理

        return chain.proceed(request);
    }
}
